﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EnnTrading.DataAccess.DBUtility;
using System.Data.SqlClient;
using System.Data;

namespace MyWCF.Demo.Client.Web.Code
{
    public class ChatRoomDB
    {
        private const string PARAM_CHAT_ROOM_ID = "@ChatRoomId";
        private const string PARAM_EVENT_ID = "@EventId";
        private const string PARAM_TITLE = "@Title";
        private const string PARAM_CREATE_TIME = "@CreateTime";
        private const string PARAM_START = "@Start";
        private const string PARAM_COUNT = "@Count";

        private static string ConnectionString = SQLHelper.CONN_STRING;
        private static void FillEntityFrom(SqlDataReader reader, ChatRoomEntity obj)
        {
            #region
            if (reader != null && !reader.IsClosed)
            {
                obj.ChatRoomId = reader.IsDBNull(reader.GetOrdinal("ChatRoomId")) ? 0 : reader.GetInt64(reader.GetOrdinal("ChatRoomId"));
                obj.EventId = reader.IsDBNull(reader.GetOrdinal("EventId")) ? 0 : reader.GetInt32(reader.GetOrdinal("EventId"));
                obj.Title = reader.IsDBNull(reader.GetOrdinal("Title")) ? String.Empty : reader.GetString(reader.GetOrdinal("Title"));
                obj.CreateTime = reader.IsDBNull(reader.GetOrdinal("CreateTime")) ? DateTime.Now : reader.GetDateTime(reader.GetOrdinal("CreateTime"));
            }
            #endregion
        }

        public static bool Add(ChatRoomEntity obj)
        {
            SqlParameter[] dbParams ={
						 SQLHelper.MakeParam(PARAM_EVENT_ID, SqlDbType.Int,0,obj.EventId),
						 SQLHelper.MakeParam(PARAM_TITLE, SqlDbType.NVarChar, 100,obj.Title)				
					};
            var result = SQLHelper.ExecuteScalar(ConnectionString, CommandType.StoredProcedure, "ChatRoom_Add", dbParams);
            if (result != DBNull.Value)
            {
                obj.ChatRoomId = long.Parse(result.ToString());
                return true;
            }
            return false;
        }

        public static List<ChatRoomEntity> GetList()
        {
            SqlDataReader reader = null;
            List<ChatRoomEntity> result = new List<ChatRoomEntity>();
            try
            {
                reader = SQLHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, "ChatRoom_GetList", null);
                while (reader.Read())
                {
                    ChatRoomEntity entity = new ChatRoomEntity();
                    FillEntityFrom(reader, entity);

                    result.Add(entity);
                }
            }
            finally
            {
                if (reader != null && reader.IsClosed == false)
                {
                    reader.Close();
                }
            }
            return result;
        }
    }
}
